package ControllerLayer;
import java.sql.SQLException;

import DBLayer.*;
import ModelLayer.*;

/**
 * @author Gruppe 2
 *
 */
public class SalesCtr {

	private SalesOrder o;
 	private IFDBOrder ifdbOrder;
	
	public SalesCtr() {
		
	}
	
	/**
	 * @return o
	 */
	public SalesOrder createSalesOrder(){
		ifdbOrder = new DBOrder();
		o = new SalesOrder();
		//date is a String, until system output can be handled.
		String date = "19900101";
		String salesOrderStatus = "Open";
		//deliveryDate is a String, until system output can be handled.
		String deliveryDate = "19910101";
		Customer c = new Customer();
		
		o.setSalesOrderDate(date);
		o.setSalesOrderStatus(salesOrderStatus);
		o.setDeliveryDate(deliveryDate);
		o.setCustomer(c);
		return o;
	}
	
	/**
	 * @param id
	 * @param quantity
	 * @throws SQLException
	 */
	public void addItem(int id, int quantity) throws SQLException {
		ProductCtr productCtr = new ProductCtr();
		try {
			Product p = productCtr.selectSingleProduct(id);
			SalesLine sl = new SalesLine(p, quantity);
			o.addSalesLine(sl);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("Product was not found");
			throw e;
		}
	}
	
	/**
	 * @param id
	 */
	public void addCustomer(int id){
		PersonCtr personCtr = new PersonCtr();
		Customer customer = personCtr.readCustomer(id);
		o.setCustomer(customer);
	}
	
	/**
	 * @param o
	 * @throws SQLException
	 */
	public void endOrder(SalesOrder o) throws SQLException {
		//Missing method in IFDBOrder and DBOrder to insert an order to the database
		try {
			ifdbOrder.insertSalesOrder(o);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("Sales order couldn't commit");
			throw e;
		}
	}
	
	/**
	 * @param orderNo
	 * @return salesOrder
	 * @throws SQLException
	 */
	public SalesOrder readSalesOrder(int orderNo) throws SQLException {
		//Insert method to read an salesOrder object.

		SalesOrder salesOrder = null;
		try {
			PersonCtr pc = new PersonCtr();
			salesOrder = ifdbOrder.selectSingleOrder(orderNo);
			salesOrder.setCustomer(pc.readCustomer(salesOrder.getCustomer().getId()));
			ProductCtr prc = new ProductCtr();
			for(SalesLine sl : salesOrder.getSalesLineArray()) {
				sl.setProduct(prc.selectSingleProduct(sl.getProduct().getProductId()));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("salesOrder was not found");
			throw e;
		}
		return salesOrder;
	}
	
	/**
	 * @param o
	 * @throws SQLException
	 */
	public void updateSalesOrder(SalesOrder o) throws SQLException {
		//Insert method to update an salesOrder object.
		try {
			ifdbOrder.updateSalesOrder(o);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("Couldn't update salesOrder");
			throw e;
		}
	}
}